﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Cms.Common;

public partial class shop_exchangeTwo : System.Web.UI.Page
{
    protected int user_id;//会员id
    public Double dTotal = 0.00; //总计款额
    public int QTotal = 0; //总计数量
    public int dintegral;//所得总积分
    public int userJifen;//会员账户积分
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Cms.Model.C_user user_model = adminUser.GetuserLoginState();//验证用户是否登录
            user_id = user_model.id;
            Application["usercard"] = user_model.usercard;
            Application["userscore"] = user_model.userscore;
            bind_exchange(user_id);

            string x = this.Request.QueryString["x"] ?? "0";
            string y = this.Request.QueryString["y"] ?? "0";
            //getStores(x, y);
            bind_Province(lbProvince);
            lbProvince.SelectedValue = "18";
        }
    }
    #region 赋值操作============
    public void bind_exchange(int user_id)
    {
        DataTable dt = new Cms.BLL.C_exchange_cart().GetList("user_id=" + user_id).Tables[0];
        if (dt != null && dt.Rows.Count > 0)
        {
            RepExchange.DataSource = dt;
            RepExchange.DataBind();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dTotal += Convert.ToDouble(dt.Rows[i]["price"]) * Convert.ToInt32(dt.Rows[i]["quantity"]);
                QTotal += Convert.ToInt32(dt.Rows[i]["quantity"]);
                dintegral += Convert.ToInt32(dt.Rows[i]["quantity"]) * Convert.ToInt32(dt.Rows[i]["integral"]);
            }
            strDintegral.Value = dintegral.ToString();
            strQTotal.Value = QTotal.ToString();
        }
        else
        {
            RepExchange.DataSource = dt;
            RepExchange.DataBind();
        }

        DataTable dtProvince = new Cms.BLL.C_Province().GetList("").Tables[0];
        if (dtProvince != null && dtProvince.Rows.Count > 0)
        {
            Province.DataSource = dtProvince;
            Province.DataBind();

        }

        DataTable dtRepeater1 = new Cms.BLL.sc_stores().GetList("location=18").Tables[0];
        if (dtRepeater1 != null && dtRepeater1.Rows.Count > 0)
        {
            Repeater1.DataSource = dtRepeater1;
            Repeater1.DataBind();

        }
        else
        {
            Repeater1.DataSource = null;
            Repeater1.DataBind();
        }
    }
    /// <summary>
    /// 绑定省
    /// </summary>
    public void bind_Province(DropDownList lbCity)
    {

        DataSet ds = new Cms.BLL.C_Province().GetList("");
        lbCity.DataSource = ds.Tables[0].DefaultView;
        lbCity.DataValueField = "ProvinceID";
        lbCity.DataTextField = "ProvinceName";
        lbCity.DataBind();
    }
    protected void lbProvince_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.lbProvince.SelectedValue == "")
        {
            return;
        }
        int txtProvince = Utils.StrToInt(lbProvince.SelectedValue.ToString(), 0);
        DataTable dtProvince = new Cms.BLL.sc_stores().GetList("location=" + txtProvince).Tables[0];
        if (dtProvince != null && dtProvince.Rows.Count > 0)
        {
            Repeater1.DataSource = dtProvince;
            Repeater1.DataBind();

        }
        else
        {
            Repeater1.DataSource = null;
            Repeater1.DataBind();
        }
    }
    protected void Province_ItemDataBound(object source, RepeaterCommandEventArgs e)
    {
        int ProvinceID = Convert.ToInt32(((HiddenField)e.Item.FindControl("Fielddocid")).Value);
        DataTable dtProvince = new Cms.BLL.sc_stores().GetList("location=" + ProvinceID).Tables[0];
        switch (e.CommandName)
        {
            case "lbtnIsMsg":
                string province = new Cms.BLL.C_Province().GetModel(ProvinceID).ProvinceName.ToString();
                //proString.InnerText = province;
                if (dtProvince != null && dtProvince.Rows.Count > 0)
                {
                    Repeater1.DataSource = dtProvince;
                    Repeater1.DataBind();

                }
                else
                {
                    Repeater1.DataSource = null;
                    Repeater1.DataBind();
                }
                break;
        }
    }
    public void getStores(string x, string y)
    {
        StringBuilder sb = new StringBuilder();
        Cms.BLL.sc_stores sc = new Cms.BLL.sc_stores();
        DataTable dtsc = sc.GetList("isHidden=0").Tables[0];

        int j = 0;

        for (int i = 0; i < dtsc.Rows.Count; i++)
        {
            double d_Location_X = double.Parse(x);
            double d_Location_Y = double.Parse(y);
            double d2_Location_X = double.Parse(dtsc.Rows[i]["latitude"].ToString());
            double d2_Location_Y = double.Parse(dtsc.Rows[i]["longitude"].ToString());
            double cd = getcalculate(d_Location_X, d_Location_Y, d2_Location_X, d2_Location_Y);


            if (cd > double.Parse("0"))
            {
                storename.Text = dtsc.Rows[i]["storename"].ToString();
                address.Text = dtsc.Rows[i]["address"].ToString();
                tel.Text = dtsc.Rows[i]["tel"].ToString();
                HiddenField1.Value = dtsc.Rows[i]["id"].ToString();
                j++;

            }
            if (j == 1)
            {
                break;
            }

        }


    }
    #region 计算地理位置距离=================================
    static double DEF_PI = 3.14159265359; // PI
    static double DEF_2PI = 6.28318530712; // 2*PI
    static double DEF_PI180 = 0.01745329252; // PI/180.0
    static double DEF_R = 6370693.5; // radius of earth

    public static double getcalculate(double mLat1, double mLon1, double mLat2, double mLon2)
    {
        double calculate;
        try
        {
            //  wxuser.setstatistics("", "微信消息ss", mLat1.ToString() + mLon1.ToString(), 0, 1);
            calculate = GetShortDistance(mLon1, mLat1, mLon2, mLat2);

            if (calculate > double.Parse("3000"))
            {
                calculate = 0;
            }
        }
        catch
        {
            calculate = 1;
        }
        return calculate;
    }
    public static double GetShortDistance(double lon1, double lat1, double lon2, double lat2)
    {
        double ew1, ns1, ew2, ns2;
        double dx, dy, dew;
        double distance;
        // 角度转换为弧度
        ew1 = lon1 * DEF_PI180;
        ns1 = lat1 * DEF_PI180;
        ew2 = lon2 * DEF_PI180;
        ns2 = lat2 * DEF_PI180;
        // 经度差
        dew = ew1 - ew2;
        // 若跨东经和西经180 度，进行调整
        if (dew > DEF_PI)
            dew = DEF_2PI - dew;
        else if (dew < -DEF_PI)
            dew = DEF_2PI + dew;
        dx = DEF_R * Math.Cos(ns1) * dew; // 东西方向长度(在纬度圈上的投影长度)
        dy = DEF_R * (ns1 - ns2); // 南北方向长度(在经度圈上的投影长度)
        // 勾股定理求斜边长
        distance = Math.Sqrt(dx * dx + dy * dy);
        return distance;
    }
    #endregion
    /// <summary>
    /// 获取产品封面图
    /// </summary>
    /// <param name="article_id"></param>
    /// <returns></returns>
    /// 
    public string getPhoto(string article_id)
    {
        string result = "";
        if (new Cms.BLL.C_article().Exists(Convert.ToInt32(article_id)))
        {
            result = new Cms.BLL.C_article().GetModel(Convert.ToInt32(article_id)).photoUrl.ToString();
        }
        return result;
    }
    /// <summary>
    /// 获取商品积分
    /// </summary>
    /// <param name="article_id"></param>
    /// <returns></returns>
    public string getIntegral(int article_id)
    {
        string result = "";
        if (new Cms.BLL.C_article().Exists(Convert.ToInt32(article_id)))
        {
            DataTable dt = new Cms.BLL.C_article_product().GetList("article_id=" + article_id).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                result = dt.Rows[0]["userscore"].ToString();
            }
        }
        return result;
    }
    /// <summary>
    /// 获取商品市场价格
    /// </summary>
    /// <param name="article_id"></param>
    /// <returns></returns>
    public string getMprice(int article_id)
    {
        string result = "";
        if (new Cms.BLL.C_article().Exists(Convert.ToInt32(article_id)))
        {
            DataTable dt = new Cms.BLL.C_article_product().GetList("article_id=" + article_id).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                result = Convert.ToDecimal(dt.Rows[0]["marketPrice"]).ToString("0.00");
            }
        }
        return result;
    }
    #endregion


    protected void RepExchange_ItemCommand(object source, RepeaterCommandEventArgs e)
    {

    }


    #region 取消操作=================
    /// <summary>
    /// 取消操作
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        Cms.Model.C_user user_model = adminUser.GetuserLoginState();//验证用户是否登录
        int result = Cms.DBUtility.DbHelperSQL.ExecuteSql("delete from C_exchange_cart where user_id=" + user_model.id);
        if (result > 0)
        {
            JscriptMsg("取消成功！", "/shop/integral.aspx", "Success");
        }
        else
        {
            JscriptMsg("取消失败！", "NotJump", "Error");
        }
    }
    #endregion

    #region 下一步操作================
    /// <summary>
    /// 下一步操作
    /// </summary>
    /// <param name="source"></param>
    /// <param name="e"></param>
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Cms.BLL.C_integral_rec bll = new Cms.BLL.C_integral_rec();
        Cms.Model.C_integral_rec model = new Cms.Model.C_integral_rec();

        Cms.BLL.C_order_integral bll_order_integral = new Cms.BLL.C_order_integral();
        Cms.Model.C_order_integral model_order_integral = new Cms.Model.C_order_integral();

        Cms.BLL.C_order_integralsub bll_order_integralsub = new Cms.BLL.C_order_integralsub();
        Cms.Model.C_order_integralsub model_order_integralsub = new Cms.Model.C_order_integralsub();

        Cms.BLL.C_user userBll = new Cms.BLL.C_user();
        Cms.Model.C_user userModel = adminUser.GetuserLoginState();
        this.user_id = userModel.id;
        this.userJifen = Convert.ToInt32(userModel.userscore);

        #region 积分兑换订单主表
        model_order_integral.order_num = Cms.Common.Utils.GetOrderNumber();//生成订单
        model_order_integral.user_id = user_id;//会员id
        model_order_integral.adress_id = 0;
        model_order_integral.quantity_sum = Convert.ToInt32(strQTotal.Value);//数量
        model_order_integral.price_sum = Convert.ToDecimal(0);
        model_order_integral.integral_sum = Convert.ToInt32(strDintegral.Value);
        model_order_integral.order_status = 0;//已预约
        model_order_integral.is_sms = 0;//是否发送短信
        model_order_integral.note = "";//备注
        model_order_integral.recommended_code = "";
        model_order_integral.updateTime = DateTime.Now;
        if (HiddenField1.Value == "")
        {
            JscriptMsg("请选择店面！", "NotJump", "Error");

        }
        else
        {
            model_order_integral.storesId = Convert.ToInt32(HiddenField1.Value.ToString());

            if (userJifen < Convert.ToInt32(strDintegral.Value))
            {
                JscriptMsg("积分不足，请兑换其他商品！", "NotJump", "Error");

            }
            else
            {
                try
                {
                    wxuser.UserSale wu = new wxuser.UserSale();
                    wu = wxuser.getUserScore(userModel.usercard, userModel.openid, model_order_integral.order_num, "兑换产品", "-" + model_order_integral.integral_sum.ToString());
                    if (wu.result == "更新成功")
                    {
                        int result = bll_order_integral.Add(model_order_integral);
                        if (result > 0)
                        {
                            DataTable dt = new Cms.BLL.C_exchange_cart().GetList("user_id=" + user_id).Tables[0];
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                for (int i = 0; i < dt.Rows.Count; i++)
                                {
                                    #region 积分兑换订单附表
                                    model_order_integralsub.article_id = Convert.ToInt32(dt.Rows[i]["article_id"]);
                                    model_order_integralsub.user_id = user_id;//会员id
                                    model_order_integralsub.order_id = result;
                                    model_order_integralsub.order_num = model_order_integral.order_num;//兑换订单号
                                    model_order_integralsub.title = dt.Rows[i]["title"].ToString();
                                    model_order_integralsub.price = Convert.ToDecimal(dt.Rows[i]["price"]);
                                    model_order_integralsub.quantity = Convert.ToInt32(dt.Rows[i]["quantity"]);//数量
                                    model_order_integralsub.integral = Convert.ToInt32(dt.Rows[i]["integral"]);
                                    model_order_integralsub.property_value = dt.Rows[i]["property_value"].ToString();
                                    model_order_integralsub.note = dt.Rows[i]["note"].ToString();
                                    model_order_integralsub.updateTime = model_order_integral.updateTime;
                                    bll_order_integralsub.Add(model_order_integralsub);

                                    #endregion

                                    #region 会员积分消费记录===========
                                    model.article_id = Convert.ToInt32(dt.Rows[i]["article_id"]);
                                    model.user_id = user_id;//会员id
                                    model.usercard = userModel.usercard;//会员卡
                                    model.openid = userModel.openid;
                                    model.numberid = model_order_integral.order_num;//兑换订单号
                                    model.scorename = dt.Rows[i]["title"].ToString();
                                    model.title = dt.Rows[i]["title"].ToString();
                                    model.wescore = Convert.ToInt32("-" + dt.Rows[0]["integral"]);//积分
                                    model.type = 1;
                                    model.updateTime = model_order_integral.updateTime;
                                    bll.Add(model);
                                    #endregion

                                    //删除积分购物车
                                    new Cms.BLL.C_exchange_cart().Delete(Convert.ToInt32(dt.Rows[i]["id"]));

                                    #region 会员积分修改================
                                    userModel.userallscore = userModel.userallscore - Convert.ToInt32(strDintegral.Value);
                                    userModel.userscore = userModel.userscore - Convert.ToInt32(strDintegral.Value);
                                    userModel.userYesScore = userModel.userYesScore + Convert.ToInt32(strDintegral.Value);
                                    userBll.Update(userModel);

                                    #endregion

                                    #region 添加到会员优惠卷表
                                    int classid = Convert.ToInt32(new Cms.BLL.C_article().GetModel(Convert.ToInt32(dt.Rows[i]["article_id"])).parentId);
                                    if (classid == 95)
                                    {
                                        for (int j = 0; j < Convert.ToInt32(dt.Rows[i]["quantity"]); j++)
                                        {
                                            Cms.BLL.C_user_coupon couponBll = new Cms.BLL.C_user_coupon();
                                            Cms.Model.C_user_coupon couponModel = new Cms.Model.C_user_coupon();
                                            couponModel.user_id = userModel.id;
                                            couponModel.coupon_id = Convert.ToInt32(dt.Rows[i]["article_id"]);
                                            couponModel.title = dt.Rows[i]["title"].ToString();
                                            couponModel.picUrl = new Cms.BLL.C_article().GetModel(Convert.ToInt32(dt.Rows[i]["article_id"])).photoUrl;
                                            couponModel.price = Convert.ToDecimal(dt.Rows[i]["price"]);
                                            couponModel.stime = DateTime.Now;
                                            couponModel.etime = DateTime.Now.AddYears(1);
                                            couponModel.number = Convert.ToInt32(dt.Rows[i]["quantity"]);
                                            couponModel.content = new Cms.BLL.C_article().GetModel(Convert.ToInt32(dt.Rows[i]["article_id"])).content;
                                            couponModel.status = 0;
                                            couponModel.type_id = 103;
                                            couponModel.updatetime = DateTime.Now;
                                            couponBll.Add(couponModel);
                                        }
                                    }
                                    #endregion
                                }
                                JscriptMsg("兑换成功！", "/shop/exchangeThree.aspx", "Success");
                            }
                            else
                            {
                                JscriptMsg("兑换失败", "NotJump", "Error");
                            }
                        }
                    }
                    else//更新失败
                    {
                        JscriptMsg("兑换失败", "NotJump", "Error");
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                    Response.End();
                }

                



            }

        }
        #endregion
    }

    #endregion

    #region 提示框=================================
    public void JscriptMsg(string msgtitle, string url, string msgcss)
    {
        string msbox = "";
        if (url == "back")
        {
            msbox = "jsdialog(\"提示\", \"" + msgtitle + "\",\"" + url + "\", \"\", \"" + msgcss + "\")";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true);
        }
        else
        {
            msbox = "jsprintWeb(\"" + msgtitle + "\", \"" + url + "\", \"" + msgcss + "\")";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true);
        }

    }
    #endregion



    protected void Repeater1_ItemDataBound(object source, RepeaterCommandEventArgs e)
    {

    }
}